class AdminController < ApplicationController
  skip_before_filter :require_login
  #before_filter :require_admin_login
  #skip_before_filter :require_admin_login, :only => [:login]

  def require_admin_login
    if session[:admin] == nil || !session[:admin].is_a?(User)
      redirect_to :action => 'login'
    end
  end

  def login

  end

  def index

  end

  def product_management
    @product = Product.search(params[:type], params[:key])
  end

  def update_product
    product_id = params[:product_id]

    if product_id

    else
      redirect_to '/admin/product_management'
    end
  end

  def new_product
    newprd_action = params[:newprd_action]

    if newprd_action
      newprd_name = params[:newprd_name]
      newprd_des = params[:newprd_des]
      newprd_type = params[:newprd_type]
      newprd_img = 'products/' + params[:newprd_img]
      newprd_price = params[:newprd_price]
      newprd_avai = 1

      Product.create(name: newprd_name,
                     description: newprd_des,
                     product_type: newprd_type,
                     available: newprd_avai,
                     image_url: newprd_img,
                     orginal_price: newprd_price
      )

      flash[:message] = 'Create product successfully !'
    end
  end

  def feedback_management
    @status = params[:status]
    @feedbacks = Feedback.find_all_by_handled(1)
    if @status == 'nothandle' || @status == nil
      @feedbacks = Feedback.find_all_by_handled(0)
    elsif @status == 'handled'
      @feedbacks = Feedback.find_all_by_handled(1)
    end
  end

  def delete_feedback
    del_status = params[:del_status]
    handle_fbs = params[:feedbackIDs]
    if del_status == nil
      del_status = 'delete'
    end

    if handle_fbs != nil
      handle_fbs.each do |handle_fb|
        fb = Feedback.find(handle_fb)
        if del_status == 'delete'
          fb.update_attribute('handled', 1)
        elsif del_status == 'restore'
          fb.update_attribute('handled', 0)
        end
      end
    end

    if del_status == 'delete'
      redirect_to '/admin/feedback_management?status=nothandle'
    else
      redirect_to '/admin/feedback_management?status=handled'
    end

  end
end
